<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 报价单
 */
quanli_require('module/base/customer/financeChange.class.php');
quanli_require('module/base/system/sysUser.class.php');
class billSale
{

    private $dbca;

    public function __construct(&$dbca)
    {
        $this->dbca = $dbca;
    }


    /**
     * 查询报价单
     */
    public function searchList(&$arg_array)
    {
        $sql = '';

        //实例用户类
        global $G_PGLOB;
        $sysUser = new sysUser( $G_PGLOB->DBCA );

        //当前登录用户信息
        $args_array = array(
            'userID' => $G_PGLOB->currentUserID
        );
        $userInfo_array = $sysUser->searchUserInfo( $args_array );
        $departmentID = $userInfo_array[0]['departmentID'];

        //订单号
        if (isset($arg_array['saleCode']) && !empty($arg_array['saleCode'])) {
            $sql .= " AND bs.saleCode LIKE '%" . trim($arg_array['saleCode']) . "%'";
        }
        //订单名称
        if (isset($arg_array['saleName']) && !empty($arg_array['saleName'])) {
            $sql .= " AND bs.saleName LIKE '%" . trim($arg_array['saleName']) . "%'";
        }
        //客户ID
        if (isset($arg_array['companyId']) && !empty($arg_array['companyId'])) {
            $sql .= " AND cm.company_id = " . $arg_array['companyId'];
        }
        //客户名称
        if (isset($arg_array['companyName']) && !empty($arg_array['companyName'])) {
            $sql .= " AND cm.company_name LIKE '%" . trim($arg_array['companyName']) . "%'";
        }
        //下单开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= " AND bs.createTime >= '" . $arg_array['startDate'] . "'";
        }
        //下单结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= " AND bs.createTime <= '" . $arg_array['endDate'] . " 23:59:59'";
        }
        //状态
        if (isset($arg_array['saleStatus']) && !empty($arg_array['saleStatus'])) {
            $sql .= " AND bs.saleStatus IN(" . $arg_array['saleStatus'] . ")";
        }
        //部门
        if (isset($arg_array['search_departmentID']) && !empty($arg_array['search_departmentID'])) {
            $sql .= " AND cm.departmentID = '" . $arg_array['search_departmentID'] . "'";
        } else{
            $sql .= " AND cm.departmentID = '" . $departmentID . "'";
        }
        //销售员
        if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
            $sql .= " AND cm.userID = '" . $arg_array['userID'] . "'";
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {
            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {
                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_sale bs
                            INNER JOIN company_master cm ON bs.companyId=cm.company_id ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }
                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
                else{
                    $sql .= ' ORDER BY bs.createTime DESC ';
                }

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
            }else{
                $sql .= ' ORDER BY bs.createTime DESC ';
            }

            $search_sql = 'SELECT bs.*, cm.userName,cm.company_name,cm.connect_name,um.trueName,um.mobile AS userMobile,ss.sendTypeName
                          FROM bill_sale bs
                          INNER JOIN company_master cm ON bs.companyId=cm.company_id 
                          LEFT JOIN user_master um ON um.userID = bs.creator 
                          LEFT JOIN sys_sendtype ss ON bs.expressId=ss.sendTypeID ' . $sql;

            $item_array = &$this->dbca->stmt_query($search_sql);

            return $item_array;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }

    //查看详情
    public function searchDtl($code)
    {
        //查询分类信息
        $search_sql = "SELECT bsd.*, gs.bigCategoryID, gs.bigCategoryName 
                      FROM bill_sale_dtl bsd
                      INNER JOIN goods_sale gs ON bsd.goodsCode=gs.postId
                      WHERE saleCode = '" . $code . "'";

        $item_array = &$this->dbca->stmt_query($search_sql);
        return $item_array;
    }

    //修改报价单状态
    public function changeStatus($param)
    {
        $bill_sale = new entity('bill_sale');
        $bill_sale->saleCode = $param["saleCode"];
        if (!$this->dbca->fetch($bill_sale)) {
            return array('code' => 400, 'message' => '未找到报价单信息');
        }

        //判断操作前的状态是否符合逻辑
        //订单状态 0:创建, 1:审核, 2:生产, 4:收货, 8:关闭, 9:取消
        if($param['status'] != 9 && $param['status'] != 3 && $bill_sale->saleStatus != ($param['status']-1)){
            return array('code' => 400, 'message' => '订单状态异常');
        }
        if($param['status'] == 1 || $param['status'] == 9 ) {
            $bill_sale->auditor = $param['operator'];
        }

        //生产
        if($param['status'] == 2) {
            $bill_sale->producer = $param['operator'];
            $bill_sale->producerDate = date('Y-m-d H:i:s');
        }
        //发货
        if($param['status'] == 3) {
            $bill_sale->sender = $param['operator'];
            $bill_sale->expressNum = $param['expressNum'];
            $bill_sale->sendDate = date('Y-m-d H:i:s');
            $bill_sale->expressTxt = $param['expressTxt'];
        }
        //收货
        if($param['status'] == 4) {
            $bill_sale->receivDate = date('Y-m-d H:i:s');
            foreach ( $param['files'] as $goodsId => $item ) {
                foreach ( $item as $num => $fileName){
                    $temp_annex = new entity('bill_temp_annex');
                    if($fileName){
                        $temp_annex->tempCode = $param['saleCode'];
                        $temp_annex->goodsId = $goodsId;
                        $temp_annex->fileName = $fileName.'.jpg';
                        $temp_annex->aType = 1;
                        $this->dbca->save($temp_annex);
                    }else{
                        $temp_annex->annexId = $num;
                        if (!$this->dbca->fetch($temp_annex)) {
                            $this->dbca->delete($temp_annex);
                        }
                    }
                }
            }
        }

        //更新发货数量
        if($param['status'] == 3 && $param['goodsArr']) {
            $money = 0;
            foreach ($param['goodsArr'] as $goods){
                $bill_sale_dtl = new entity('bill_sale_dtl');
                $bill_sale_dtl->goodsId = $goods['goodsId'];
                if ($this->dbca->fetch($bill_sale_dtl)) {
                    $bill_sale_dtl->sendAmount = $bill_sale_dtl->sendAmount+$goods['amount'];
                    $this->dbca->save($bill_sale_dtl);
                    $money = ($goods['recordBeatingCost'] + $goods['recordPrice']) * $goods['amount'] + $money;
                    //发货日志
                    $bill_sale_send = new entity('bill_sale_send');
                    $bill_sale_send->saleCode = $param['saleCode'];
                    $bill_sale_send->expressNum = $param['expressNum'];
                    $bill_sale_send->freight = $param['freight'];
                    $bill_sale_send->expressTxt = $param['expressTxt'];
                    $bill_sale_send->creator = $param['operator'];
                    $bill_sale_send->goodsId = $goods['goodsId'];
                    $bill_sale_send->goodsName = $goods['goodsName'];
                    $bill_sale_send->packageName = $goods['packageName'];
                    $bill_sale_send->amount = $goods['amount'];
                    $this->dbca->save($bill_sale_send);
                }
            }
            $money = $money + $param['freight'];
            $array['saleCode'] = $param['saleCode'];
            $array['paymentMethod'] = 523;
            $array['changeAmount'] = $money;
            $array['custID'] = $param['companyId'];
            $array['custName'] = $param['companyName'];
            global $G_PGLOB;

            $financeChange = new financeChange( $G_PGLOB->DBCA );

            $array['creator'] = $G_PGLOB->currentUserName;

            $financeChange->saveAccountChange( $array);

        }

        $bill_sale->saleStatus = $param['status'];
        $this->dbca->save($bill_sale);
        return array('code' => 200, 'data'=>$bill_sale);
    }

    //保存报价单
    public function save($param)
    {
        $bill_sale = new entity('bill_sale');
        if(isset($param['saleCode']) && !empty($param['saleCode'])){
            $bill_sale->saleCode = $param['saleCode'];
            if(!$this->dbca->fetch($bill_sale)){
                return array('code' => 400, 'message' => '未找到销售订单信息');
            }
        }else {
            $bill_sale->saleCode = generate_seqno('seqno_sale', 'S');
            $bill_sale->creator = $param['operator'];
        }

        $bill_sale->saleStatus = 0;
        $bill_sale->companyId = $param['companyId'];
        $bill_sale->saleName = $param['saleName'];
        $bill_sale->area = $param['area'];
        $bill_sale->categoryName = $param['categoryName'];
        $bill_sale->expressId = $param['expressId'];
        $bill_sale->request = $param['request'];
        $bill_sale->requestDate = $param['requestDate'];
        $bill_sale->receiver = $param['receiver'];
        $bill_sale->receivMobile = $param['receivMobile'];
        $bill_sale->province = $param['province'];
        $bill_sale->provinceName = $param['provinceName'];
        $bill_sale->city = $param['city'];
        $bill_sale->cityName = $param['cityName'];
        $bill_sale->county = $param['county'];
        $bill_sale->countyName = $param['countyName'];
        $bill_sale->address = $param['address'];
        $bill_sale->remark = $param['remark'];

        $this->dbca->beginTransaction();

        try{
            $this->dbca->save($bill_sale);
            if(isset($param['saleCode']) && !empty($param['saleCode'])) {
                $this->dbca->stmt_query('DELETE FROM bill_sale_dtl WHERE saleCode = ?', 's', $param['saleCode']);
            }
            foreach ($param['dtl'] as $goods) {
                $dtl = new entity('bill_sale_dtl');
                $dtl->creator = $param['operator'];
                $dtl->saleCode = $bill_sale->saleCode;
                $dtl->categoryId = $goods['goodsCategoryId'];
                $dtl->categoryName = $goods['goodsCategoryName'];
                $dtl->goodsCode = $goods['goodsCode'];
                $dtl->t_goodsId = $goods['t_goodsId'];
                $dtl->goodsName = $goods['goodsName'];
                $dtl->color = $goods['color'];
                $dtl->colorDis = $goods['colorDis'];
                $dtl->amount = $goods['amount'];
                $dtl->packageId = $goods['packageId'];
                $dtl->packageName = $goods['packageName'];
                $dtl->specId = $goods['specId'];
                $dtl->specName = $goods['specName'];
                $dtl->price = $goods['price'];
                $dtl->beatingCost = $goods['beatingCost'];
                $this->dbca->save($dtl);
                if(!empty($goods['t_goodsId'])){
                    $this->dbca->stmt_query('DELETE FROM bill_temp_annex WHERE aType=1 AND goodsId = ?', 's', $goods['t_goodsId']);
                    $item_array = &$this->dbca->stmt_query('SELECT * FROM bill_temp_annex WHERE aType=0 AND goodsId=?', 's', $goods['t_goodsId']);
                    if($item_array){
                        foreach ($item_array as $tempAnnex){
                            $newAnnex = new entity('bill_temp_annex');
                            $newAnnex->tempCode = $bill_sale->saleCode;
                            $newAnnex->goodsId = $dtl->LAST_INSERT_ID;
                            $newAnnex->fileName = $tempAnnex->fileName;
                            $newAnnex->aType = 1;
                            $this->dbca->save($newAnnex);
                        }
                    }
                }
            }
            $this->dbca->commit();
            return array('code' => 200 , 'message' => 'ok');

        }catch (Exception $e){
            elog($e->getMessage());
            $this->dbca->rollBack();
        }
        return array('code' => 500 , 'message' => '系统错误，保存失败');

    }

    //查看附件
    public function searchAnnex($code)
    {
        $search_sql = "SELECT bta.*,bsd.categoryName,bsd.goodsName FROM bill_temp_annex bta
        INNER JOIN bill_sale_dtl bsd ON bta.goodsId=bsd.goodsId
        WHERE bta.aType=1 AND bta.tempCode = '" . $code . "'";

        $item_array = &$this->dbca->stmt_query($search_sql);
        return $item_array;
    }

    //查看发货信息
    public function saleSend($code)
    {
        $search_sql = "SELECT * FROM bill_sale_send WHERE saleCode = '" . $code . "'ORDER BY createTime DESC , goodsName DESC";
        //$search_sql = "SELECT DISTINCT  expressNum FROM bill_sale_send WHERE saleCode = '" . $code . "'ORDER BY createTime DESC , goodsName DESC";

        $item_array = &$this->dbca->stmt_query($search_sql);
        return $item_array;
    }

    //修改商品价格
    public function savePrice(){
        $bill_sale_dtl = new entity('bill_sale_dtl');
        $bill_sale_dtl->uuid = $_REQUEST['uuid'];
        if(!$this->dbca->fetch($bill_sale_dtl)){
            return array('code' => 400, 'message' => '未找到此商品信息');
        }else{
            $search_sql = "SELECT * FROM bill_sale_dtl WHERE uuid = '" . $_REQUEST['uuid'] . "'";
            $item = &$this->dbca->stmt_query($search_sql);
            $item = $item[0];
            $bill_sale_dtl->uuid = $_REQUEST['uuid'];
            $bill_sale_dtl->price = $_REQUEST['price'];
            $bill_sale_dtl->beatingCost = $_REQUEST['beatingCost'];
            if($this->dbca->save($bill_sale_dtl)){
                $price_log = new entity('bill_sale_dtl_price_log');
                $price_log->saleCode = "$item->saleCode";
                $price_log->goodsCode = $item->goodsCode;
                $price_log->goodsName = $item->goodsName;
                $price_log->creator = $_REQUEST['operator'];
                $price_log->price = $item->price;
                $price_log->savePrice = $_REQUEST['price'];
                $price_log->beatingCost = $item->beatingCost;
                $price_log->saveBeatingCost = $_REQUEST['beatingCost'];
                $this->dbca->save($price_log);
            }
            return array('code' => 200, 'data'=>'ok');
        }

    }

    /**
     * 导出查询销售订单
     */
    public function searchListExcel(&$arg_array)
    {
        $sql = '';

        //实例用户类
        global $G_PGLOB;
        $sysUser = new sysUser( $G_PGLOB->DBCA );

        //当前登录用户信息
        $args_array = array(
            'userID' => $G_PGLOB->currentUserID
        );
        $userInfo_array = $sysUser->searchUserInfo( $args_array );
        $departmentID = $userInfo_array[0]['departmentID'];

        //订单号
        if (isset($arg_array['saleCode']) && !empty($arg_array['saleCode'])) {
            $sql .= " AND bs.saleCode LIKE '%" . trim($arg_array['saleCode']) . "%'";
        }
        //订单名称
        if (isset($arg_array['saleName']) && !empty($arg_array['saleName'])) {
            $sql .= " AND bs.saleName LIKE '%" . trim($arg_array['saleName']) . "%'";
        }
        //客户ID
        if (isset($arg_array['companyId']) && !empty($arg_array['companyId'])) {
            $sql .= " AND cm.company_id = " . $arg_array['companyId'];
        }
        //客户名称
        if (isset($arg_array['companyName']) && !empty($arg_array['companyName'])) {
            $sql .= " AND cm.company_name LIKE '%" . trim($arg_array['companyName']) . "%'";
        }
        //下单开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= " AND bs.createTime >= '" . $arg_array['startDate'] . "'";
        }
        //下单结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= " AND bs.createTime <= '" . $arg_array['endDate'] . " 23:59:59'";
        }
        //状态
        if (isset($arg_array['saleStatus']) && !empty($arg_array['saleStatus'])) {
            $sql .= " AND bs.saleStatus IN(" . $arg_array['saleStatus'] . ")";
        }
        //部门
        if (isset($arg_array['search_departmentID']) && !empty($arg_array['search_departmentID'])) {
            $sql .= " AND cm.departmentID = '" . $arg_array['search_departmentID'] . "'";
        }else{
            $sql .= " AND cm.departmentID = '" . $departmentID . "'";
        }
        //销售员
        if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
            $sql .= " AND cm.userID = '" . $arg_array['userID'] . "'";
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {
            $sql .= ' ORDER BY bs.createTime DESC ';
            $search_sql = 'SELECT bs.*, cm.userName,cm.company_name,cm.connect_name,um.trueName,um.mobile AS userMobile,ss.sendTypeName
                          FROM bill_sale bs
                          INNER JOIN company_master cm ON bs.companyId=cm.company_id 
                          LEFT JOIN user_master um ON um.userID = bs.creator 
                          LEFT JOIN sys_sendtype ss ON bs.expressId=ss.sendTypeID ' . $sql;
            $item_array = &$this->dbca->stmt_query($search_sql);
            $saleStatus = array(0=>'创建', 1=>'审核', 2=>'生产',3=>'已发货', 4=>'收货', 8=>'关闭', 9=>'取消');
            foreach($item_array as $val){
                $freight_sql = "SELECT SUM(freight) AS freightCount FROM bill_sale_send WHERE saleCode='".$val->saleCode."'";
                $freightCount = &$this->dbca->stmt_query($freight_sql);
                $freight_sql = "SELECT SUM((price + beatingCost)* amount) AS totalAmount FROM bill_sale_dtl WHERE saleCode='".$val->saleCode."'";
                $total_amount = &$this->dbca->stmt_query($freight_sql);
                $list[] = array(
                    'saleCode' => $val->saleCode,
                    'createTime' => $val->createTime,
                    'userName' => $val->userName,
                    'saleStatus' => $saleStatus[$val->saleStatus],
                    'company_name' => $val->company_name,
                    'total_amount' => $total_amount[0]->totalAmount,
                    'freightCount' => $freightCount[0]->freightCount,
                    'saleName' => $val->saleName,
                    'area' => $val->area,
                    'categoryName' => $val->categoryName,
                    'requestDate' => $val->requestDate,
                    'request' => $val->request,
                    'expressId' => $val->sendTypeName,
                    'receiver' => $val->receiver,
                    'receivMobile' => $val->receivMobile,
                    'provinceName' => $val->provinceName,
                    'cityName' => $val->cityName,
                    'countyName' => $val->countyName,
                    'address' => $val->address,
                    'remark' => $val->remark
                );
            }
            foreach ($list as &$val){
                    $del_sql = "SELECT categoryName AS productSeries,goodsName,color,colorDis,packageName,specName,price,beatingCost,(price+beatingCost) AS actualPrice,amount,sendAmount FROM bill_sale_dtl WHERE saleCode='".$val['saleCode']."'";
                    $del = &$this->dbca->stmt_query($del_sql);
                    foreach($del as $v){
                        $sale_del[] = array(
                            'productSeries' => $v->productSeries,
                            'goodsName' => $v->goodsName,
                            'color' => $v->color,
                            'colorDis' => $v->colorDis,
                            'packageName' => $v->packageName,
                            'specName' => $v->specName,
                            'price' => $v->price,
                            'beatingCost' => $v->beatingCost,
                            'actualPrice' => $v->actualPrice,
                            'amount' => $v->amount,
                            'sendAmount' => $v->sendAmount
                        );
                    }
                    $val['saleDel'] = $sale_del;
                    $val['saleDelCount'] = count($sale_del);
                    $sale_del = null;
            }
            return $list;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }
}